<template>
  <div class="app-container">
    <el-form ref="userFormRef" :model="form" label-width="auto" style="min-width: 600px">
      <el-form-item label="选择主题表" style="display: flex">
        <el-select v-model="form.themeTableId" @change="handleThemeTableSelectChange">
          <el-option
            v-for="item in topicOptions"
            :key="item.id"
            :label="item.tableName"
            :value="item.id!"
          />
        </el-select>
        <el-button type="info" size="small" @click="createThemeTable">新建主题表</el-button>
      </el-form-item>
      <el-form-item label="选择数据期列">
        <el-select v-model="form.timeColumn">
          <el-option
            v-for="item in timeColumnOptions"
            :key="item.id"
            :label="item.timeColumn"
            :value="item.id!"
          />
        </el-select>
      </el-form-item>
      <h3>主题表增量固化信息</h3>
      <el-form-item label="获取效据期的数据">
        <el-select v-model="form.dataPeriod">
          <el-option
            v-for="item in dataPeriodOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <!-- 当选择自定义数据期时显示富文本框和帮助按钮 -->
        <div
          v-if="form.dataPeriod === '自定义数据期'"
          style="display: inline-block; margin-left: 20px; vertical-align: top"
        >
          <el-input
            v-model="form.dataPeriod"
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 6 }"
            placeholder="请输入自定义数据期"
          />
          <el-button type="info" size="small" @click="showRuleExplanation">帮助</el-button>
        </div>
      </el-form-item>
      <h3>主题表固化周期信息</h3>
      <el-form-item label="执行周期">
        <el-select v-model="form.executionCycle" @change="handleCycleChange">
          <el-option
            v-for="item in executionCycleOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <!-- 当选择自定义执行周期时显示from表单 -->
        <div style="display: inline-block; margin-left: 20px; vertical-align: top">
          <el-form :inline="true" :model="form" class="cycle-form-inline">
            <el-form-item
              v-if="form.executionCycle === '每月' || form.executionCycle === '每年'"
              label="每年的第"
            >
              <el-select v-model="form.month">
                <el-option v-for="month in months" :key="month" :label="month" :value="month" />
              </el-select>
              月
            </el-form-item>
            <el-form-item v-if="form.executionCycle === '每周'" label="每周：">
              <el-select v-model="form.week">
                <el-option v-for="week in weeks" :key="week" :label="week" :value="week" />
              </el-select>
            </el-form-item>
            <el-form-item
              v-if="form.executionCycle === '每月' || form.executionCycle === '每年'"
              label="每月的第"
            >
              <el-select v-model="form.day">
                <el-option v-for="day in days" :key="day" :label="day" :value="day" />
              </el-select>
              天
            </el-form-item>
            <el-form-item
              v-if="
                form.executionCycle === '每月' ||
                form.executionCycle === '每年' ||
                form.executionCycle === '每周' ||
                form.executionCycle === '每日'
              "
              label="每日的："
            >
              <el-time-picker
                v-model="form.time"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="选择时间"
                @change="handleTimeChange"
              />
            </el-form-item>
            <el-form-item v-if="form.executionCycle === '自定义执行周期'" label="自定义表达式">
              <el-input
                v-model="form.customizeExecutionCycle"
                type="textarea"
                :autosize="{ minRows: 3, maxRows: 6 }"
                placeholder="请输入自定义执行周期"
                clearable
              />
              <div>
                <el-button type="info" size="small" @click="showRuleExplanationExecutionCycle">
                  帮助
                </el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </el-form-item>
    </el-form>
    <!-- 规则说明弹窗 -->
    <el-dialog v-model="ruleExplanationVisible" width="70%" title="自定义数据期规则说明" center>
      <pre>{{ ruleExplanationHtml }}</pre>
      <template #footer>
        <el-button @click="ruleExplanationVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="cycleRuleVisible" width="70%" title="自定义执行周期规则说明" center>
      <pre>{{ ruleExplanationHtml }}</pre>
      <template #footer>
        <el-button @click="cycleRuleVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
  <el-dialog
    v-model="isCreateVisble"
    title="新建主题表"
    :fullscreen="true"
    destroy-on-close
    center
    @close="handleCloseThemeTableDialog"
  >
    <CreateThemeTable
      :data-source-id="dataSourceId"
      :data-source-name="dataSourceName"
      @success="handleSaveNewTable"
      @close="closedDialog"
    />
  </el-dialog>
  <div class="footer mb-4">
    <el-button type="success" size="large" @click="saveConfiguration">保存</el-button>
    <el-button type="danger" size="large" @click="resetConfiguration">重置</el-button>
  </div>
</template>
<script lang="ts">
export default { name: "CuredConfiguration" };
</script>
<script setup lang="ts">
import IndicatorSolidifyAPI, {
  TopicOptions,
  TimeColumnOptions,
  Solidify,
  IdRequestParameter,
} from "@/api/indicatorSolidification/index";
import CreateThemeTable from "../../indicationManage/themeDomainComponent/createThemeTable.vue";
import dataPeriodRuleConfig from "../ruleFile/dataPeriodRuleExplanation.txt?raw";
import executionCycleRuleConfig from "../ruleFile/executionCycleRuleConfig.txt?raw";
const props = defineProps<{
  id?: number;
}>();
const form = ref<Solidify>({
  month: "1", // 默认一月
  week: "周一", // 默认周一
  day: "1", // 默认第一天
  time: "00:00", // 默认00:00
  customizeExecutionCycle: "",
});

const userFormRef = ref();

const handleTimeChange = (time: string | null) => {
  form.value.time = time!;
  console.log("选择的时间：", time);
};

const emit = defineEmits(["save", "reset"]);

const dataSourceId = ref(0);
const dataSourceName = ref("");

const isCreateVisble = ref(false);
const insertQuery = reactive<Solidify>({});
const idQuery = reactive<IdRequestParameter>({});
const timeListParameter = reactive<IdRequestParameter>({});

const formInline = ref({
  month: "1", // 默认一月
  week: "周一", // 默认周一
  day: "1", // 默认第一天
  time: "00:00", // 默认00:00
  customize: "",
});

// 修改时间选择器的绑定方式，避免直接绑定到formInline
// const selectedTime = ref<string | null>("00:00:00");

const topicOptions = ref<TopicOptions[]>();
const timeColumnOptions = ref<TimeColumnOptions[]>();
// 生成月份数组
const months = Array.from({ length: 12 }, (_, i) => i + 1);
// 生成星期数组
const weeks = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];
// 生成每月天数数组
const days = Array.from({ length: 31 }, (_, i) => i + 1);

const dataPeriodOptions = [
  {
    label: "全量固化",
    value: "全量固化",
  },
  {
    label: "本期",
    value: "本期",
  },
  {
    label: "上期",
    value: "上期",
  },
  {
    label: "本季",
    value: "本季",
  },
  {
    label: "本年",
    value: "本年",
  },
  {
    label: "自定义数据期",
    value: "自定义数据期",
  },
];

const executionCycleOptions = [
  {
    label: "每日",
    value: "每日",
  },
  {
    label: "每周",
    value: "每周",
  },
  {
    label: "每月",
    value: "每月",
  },
  {
    label: "每年",
    value: "每年",
  },
  {
    label: "自定义执行周期",
    value: "自定义执行周期",
  },
];

// 富文本框输入内容
const customDataPeriodInput = ref("");
// 规则说明弹窗显示状态
const ruleExplanationVisible = ref(false);
const cycleRuleVisible = ref(false);
// 规则说明 HTML 内容
const ruleExplanationHtml = ref("");
const cycleRuleConfig = ref("");

// 显示规则说明弹窗
const showRuleExplanation = () => {
  ruleExplanationVisible.value = true;
};

const showRuleExplanationExecutionCycle = () => {
  cycleRuleVisible.value = true;
};

function loadingRuleConfig() {
  ruleExplanationHtml.value = dataPeriodRuleConfig;
  cycleRuleConfig.value = executionCycleRuleConfig;
}

const createThemeTable = () => {
  isCreateVisble.value = true;
};

const handleQuery = async () => {
  const response = await IndicatorSolidifyAPI.TableList();
  topicOptions.value = response;
};

const handleInfoQuery = (id?: number) => {
  idQuery.id = id;
  IndicatorSolidifyAPI.Info(idQuery).then((data) => {
    console.log(data);
    form.value = data;
  });
};

const handleCloseThemeTableDialog = () => {
  handleQuery();
  console.log("关闭模态框");
};

// 新建主题表成功后，关闭弹窗
const handleSaveNewTable = (themeTableData: { dataSourceId: number; themeTableId: number }) => {
  isCreateVisble.value = false;
  handleQuery();
  form.value.themeTableId = themeTableData.themeTableId;
  dataSourceId.value = themeTableData.dataSourceId;
};

// 新建主题表页面关闭后
const closedDialog = () => {
  isCreateVisble.value = false;
  handleQuery();
  form.value.themeTableId = null;
  dataSourceId.value = null;
};

const handleThemeTableSelectChange = async () => {
  timeListParameter.id = form.value.themeTableId;
  IndicatorSolidifyAPI.TimeColumnList(timeListParameter).then((data) => {
    timeColumnOptions.value = data;
  });
};

// 处理执行周期变化
const handleCycleChange = (value: string) => {
  console.log("当前执行周期", value);
  // // 重置所有相关字段，避免旧值影响
  // form.value = {
  //   month: "1",
  //   week: "周一",
  //   day: "1",
  //   time: "00:00:00",
  //   customizeExecutionCycle: "",
  // };
  // 仅重置相关字段，保留executionCycle等其他属性
  form.value.month = "1";
  form.value.week = "周一";
  form.value.day = "1";
  form.value.time = "00:00";
  form.value.customizeExecutionCycle = "";

  // 根据选择的周期设置默认值
  switch (value) {
    case "每日":
      // 默认每日00:00执行
      form.value.time = "00:00";
      break;
    case "每周":
      // 默认每周一00:00执行
      form.value.week = "周一";
      form.value.time = "00:00";
      break;
    case "每月":
      // 默认每月第一天00:00执行
      form.value.day = "1";
      form.value.time = "00:00";
      break;
    case "每年":
      // 默认每年第一个月第一天00:00执行
      form.value.month = "1";
      form.value.day = "1";
      form.value.time = "00:00";
      break;
    case "自定义执行周期":
      // 清空自定义表达式
      form.value.customizeExecutionCycle = "";
      break;
  }
};

// 添加保存和重置方法
const saveConfiguration = useDebounceFn(() => {
  // 构建保存参数
  const saveParams = {
    ...form.value,
    ...insertQuery,
  };

  console.log("保存配置:", saveParams); // 临时调试
  emit("save"); // 通知父组件保存成功
  userFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const solidifyId = form.value.id;
      if (solidifyId) {
        IndicatorSolidifyAPI.Update(saveParams).then(() => {
          ElMessage.success("修改成功");
          emit("save"); // 通知父组件保存成功
        });
      } else {
        IndicatorSolidifyAPI.Insert(saveParams).then(() => {
          ElMessage.success("新增成功");
          emit("save"); // 通知父组件保存成功
        });
      }
    }
  });
}, 1000);

const resetConfiguration = () => {
  // 重置表单
  form.value = {
    themeTableId: 0,
    timeColumn: "",
    dataPeriod: "",
    executionCycle: "",
  };

  form.value = {
    month: "1",
    week: "周一",
    day: "1",
    time: "",
    customizeExecutionCycle: "",
  };

  emit("reset"); // 通知父组件已重置
};

onMounted(() => {
  handleQuery();
  loadingRuleConfig();
  if (props.id) {
    handleInfoQuery(props.id);
  }
});
</script>
<style lang="scss" scoped>
.cycle-form-inline .el-input {
  --el-input-width: 220px;
}

.cycle-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
